<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="审批单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalCode">
              <a-input v-model="model.approvalCode" placeholder="请输入审批单号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalType">
              <j-dict-select-tag type="list" v-model="model.approvalType" dictCode="sales_collection_approval" placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="销售回款管理" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="salesCollectionManagementDetailTable.loading"
          :columns="salesCollectionManagementDetailTable.columns"
          :dataSource="salesCollectionManagementDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction, postAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

  export default {
    name: 'SalesCollectionManagementForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          id:null,
          approvalCode:"",
          approvalType:"",
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           approvalType: [
              { required: true, message: '请输入审批流程!'},
           ],
        },
        refKeys: ['salesCollectionManagementDetail', ],
        tableKeys:['salesCollectionManagementDetail', ],
        activeKey: 'salesCollectionManagementDetail',
        // 销售回款管理
        salesCollectionManagementDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '订单编号',
              key: 'schedulingNumber',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '发货金额',
              key: 'shipmentAmount',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '已回款金额',
              key: 'alreadyPayment',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '未回款金额',
              key: 'unPayment',
               type: JVXETypes.input,
               disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '本次回款(支付)',
              key: 'nowPayment',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '本次回款(到账)',
              key: 'nowDaozhang',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '回款日期',
              key: 'paymentDate',
              type: JVXETypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/procurement/salesCollectionManagement/add",
          edit: "/procurement/salesCollectionManagement/edit",
          queryById: "/procurement/salesCollectionManagement/queryById",
          salesCollectionManagementDetail: {
            list: '/procurement/salesCollectionManagement/querySalesCollectionManagementDetailByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      customFormData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false,
      },
    },
    computed: {
      formDisabled() {
        if (this.customFormData != null && this.customFormData.id) {
          this.disabled = false
        }
        return this.disabled
      },
    },
    created () {
      console.log('this.customFormData1=', this.customFormData)
      if(this.customFormData != null&&this.customFormData[0].id){} {
        this.model=this.customFormData[0];
        this.salesCollectionManagementDetailTable.dataSource=this.customFormData;
        console.log("this.customFormData=",this.customFormData);
        this.$forceUpdate()
      }
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model))
      this.initDictConfig()
      //this.editAfter() //现在子表内容需要
    },
    methods: {
      applySubmit(record) {
        console.log("aaaaaaaarecord")
        if (record.dataId && record.dataId.length < 1) {
          this.$message.error('审批时必须传入参数dataId')
          return
        }

        //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
        isFirstInitiator(record.dataId, record).then((res) => {
          if (res.success && res.result) {
            // 只有第一次能自动申请
            return
          } else {
            var params = Object.assign(
              {
                dataId: record.dataId,
              },
              record
            )
            definitionStartByDataId(record.dataId, 'salesCollectionManagementService', params)
              .then((res) => {
                if (res.success) {
                  this.$message.success(res.message)
                } else {
                  this.$message.error(res.message)
                }
              })
              .finally()
          }
        })
      },
      add(record){
        console.log("2222222222333333333",record)
        this.salesCollectionManagementDetailTable.dataSource[0]=record[0]
        console.log("2232323232111111",this.salesCollectionManagementDetailTable.dataSource)
      },
      submitForm(){
        console.log("211111111111111",this.model)
        if(this.model.id===null){
          console.log("32131添加",this.model)
          const row = this.salesCollectionManagementDetailTable.dataSource[0] || {};
          this.model = {
            ...this.model,                 // 主表原有字段
            ...row,                        // 子表行字段
            approvalType: this.model.approvalType,
            approvalCode: this.model.approvalCode,
          };
          this.model.id=null
          if(this.model.approvalCode===null||this.model.approvalType===""){
            return this.$message.error("请选择审批类型")
          }
          if(this.model.nowPayment===null ){
            return this.$message.error("请输入本次回款（付款）")
          }
          if(this.model.nowDaozhang===null ){
            return this.$message.error("请输入本次回款（到账）")
          }
          if (this.model.nowPayment>this.model.unPayment){
            return this.$message.error("付款金额不能大于未付款金额")
          }
          console.log("sbumit2222222222",this.model)
          postAction(this.url.add,this.model).then((res)=>{
            if(res.success){
              this.$message.success("添加成功")
              this.$emit('ok')
              this.close()
            }
          })
        }else {
          console.log("32131编辑",this.model)
          console.log("edit2222222222",this.model)
          postAction(this.url.edit,this.model).then((res)=>{
            if(res.success){
              this.$message.success("编辑成功")
              this.$emit('ok')
              this.close()
            }
          })
        }
      },
      addBefore(){
        this.salesCollectionManagementDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        this.salesCollectionManagementDetailTable.dataSource[0]=this.model
        /*if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.salesCollectionManagementDetail.list, params, this.salesCollectionManagementDetailTable)
        }*/
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          salesCollectionManagementDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>